<template>
  <div class="app-container">
    <div class="header">
      <h1 class="title">用户管理</h1>
      <el-button type="primary" @click="handleAdd" class="add-btn">新增用户</el-button>
    </div>

    <el-table :data="userinfo" style="width: 100%; margin-top: 20px;" class="user-table">
      <el-table-column label="头像" width="80">
        <template slot-scope="scope">
          <img :src="scope.row.avatarUrl" alt="Avatar" class="table-avatar" v-if="scope.row.avatarUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column prop="createdAt" label="注册日期"></el-table-column>
      <el-table-column prop="isActive" label="是否激活" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isActive" :active-value="1" :inactive-value="0" disabled></el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template slot-scope="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        <el-button size="small" type="warning"
          @click="resetPasswordDialogVisible = true; Object.assign(resetPasswordForm, { id: scope.row.userId })">重置密码</el-button>
      </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/新增 用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" class="dialog">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option v-for="role in roles" :key="role.roleId" :label="role.description"
              :value="role.description"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否激活" prop="isActive">
          <el-switch v-model="editForm.isActive" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="头像" prop="avatarUrl">
          <img :src="editForm.avatarUrl" class="avatar">
        </el-form-item>
        <!-- 密码字段仅在新增用户时显示 -->
        <el-form-item v-if="!editForm.id" label="密码" prop="password">
          <el-input type="password" v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item v-if="!editForm.id" label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="editForm.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">{{ editForm.id ? '修 改' : '新 增' }}</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" :visible.sync="resetPasswordDialogVisible" width="30%" @closed="handleDialogClosed">
      <el-form :model="resetPasswordForm" :rules="resetPasswordRules" ref="resetPasswordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input type="password" v-model="resetPasswordForm.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="resetPasswordForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmNewPassword">
          <el-input type="password" v-model="resetPasswordForm.confirmNewPassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmResetPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  data() {
    return {
      dialogVisible: false,
      resetPasswordDialogVisible: false,
      dialogTitle: '',
      editForm: {
        id: null,
        username: '',
        email: '',
        phone: '',
        role: '', // 注意这里使用的是角色描述而非 roleId
        avatarUrl: '',
        isActive: 1, // 默认激活状态
      },
      resetPasswordForm: {
        id: null,
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' } // 添加验证器
        ]
      },
      resetPasswordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        confirmNewPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: this.validateNewPassword, trigger: 'blur' } // 添加验证器
        ]
      }
    };
  },
  computed: {
    ...mapState('user', ['userinfo', 'roles'])
  },
  methods: {
    ...mapActions('user', [
      'loadUsersRole',
      'addNewUser',
      'editExistingUser',
      'deleteUserById',
      'resetUserPassword',
      'fetchRoles'
    ]),
    validatePassword(rule, value, callback) {
      if (value !== this.editForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    validateNewPassword(rule, value, callback) {
      if (value !== this.resetPasswordForm.newPassword) {
        callback(new Error('两次输入的新密码不一致'));
      } else {
        callback();
      }
    },
    handleAdd() {
      this.dialogTitle = '新增用户';
      this.editForm = {
        avatarUrl: 'https://wx2.sinaimg.cn/mw690/d315af46ly1hnn5btbjr5j20j60j7mzv.jpg' // 设置默认头像地址
      };
      this.dialogVisible = true;
    },
    handleEdit(index, row) {
      this.dialogTitle = '编辑用户';
      Object.assign(this.editForm, row);
      this.editForm.id = row.userId; // 确保编辑模式下有 ID 属性
      delete this.editForm.password; // 确保编辑模式下没有密码属性
      delete this.editForm.confirmPassword; // 确保编辑模式下没有确认密码属性
      this.dialogVisible = true;
    },
    async submitForm() {
      try {
        const isValid = await this.$refs['editForm'].validate();
        if (!isValid) return;

        // 分离 id 和其他用户数据，以便正确传递给 editExistingUser 或 addNewUser
        const { id, ...formData } = this.editForm;

        // 确定要调用的方法名
        const action = id ? 'editExistingUser' : 'addNewUser';

        // 调用 Vuex 中的相应方法，并传递正确的参数
        await this[action]({ id, ...formData });

        // 检查响应以确定操作是否成功
          this.dialogVisible = false;
          this.$message({
            message: id ? '编辑用户成功' : '新增用户成功',
            type: 'success'
          });
          // 刷新用户列表
          await this.loadUsersRole();
      } catch (error) {
        this.$message({
          message: '操作失败，请检查输入信息或稍后再试。',
          type: 'error'
        });
        console.error('提交表单时发生错误:', error);
      }
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.deleteUserById(row.userId); // 使用 userId 进行删除操作
          this.$message({
            message: '用户删除成功',
            type: 'success'
          });
          // 刷新用户列表
          await this.loadUsersRole();
        } catch (error) {
          // this.$message({
          //   message: '删除失败，请稍后再试。',
          //   type: 'error'
          // });
          console.error('删除用户时发生错误:', error);
        }
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'info'
        });
      });
    },
  confirmResetPassword() {
      this.$refs['resetPasswordForm'].validate(async valid => {
        if (valid) {
          try {
            // 更新用户密码逻辑...
            await this.resetUserPassword({
              id: this.resetPasswordForm.id,
              oldPassword: this.resetPasswordForm.oldPassword,
              newPassword: this.resetPasswordForm.newPassword
            });

            this.$message({
              message: '密码重置成功',
              type: 'success'
            });

            // 清空表单
            this.resetPasswordForm = {
              id: null,
              oldPassword: '',
              newPassword: ''
            };

            // 关闭对话框
            this.resetPasswordDialogVisible = false;
          } catch (error) {
            // this.$message({
            //   message: '密码重置失败，请检查输入信息或稍后再试。',
            //   type: 'error'
            // });
            console.error('重置密码时发生错误:', error);
          }
        }
      });
    },
    handleDialogClosed() {
      // 清空表单数据
      this.resetPasswordForm = {
        id: null,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      // 如果您的表单组件有内置的重置方法，也可以使用它
      this.$refs['resetPasswordForm'].resetFields();
    },

    closeDialog() {
      this.resetPasswordDialogVisible = false;
    }
  },
  mounted() {
    // 初始化加载用户列表
    this.loadUsersRole();
    this.fetchRoles();
  }
};
</script>





<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.header {
  display: flex;
  justify-content: center;
  /* 标题居中 */
  align-items: center;
  position: relative;
  margin-bottom: 20px;
}

.title {
  color: #303133;
  flex-grow: 1;
  /* 让标题占据剩余空间 */
  text-align: center;
  /* 确保文本居中 */
}

.add-btn {
  position: absolute;
  right: 0;
  /* 固定按钮到右侧 */
}

.user-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.dialog {
  border-radius: 8px;
}

.form {
  max-width: 400px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.avatar-uploader.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader.el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  display: block;
}
</style>